/**
 * 房間事件類
 * 
 */
function roomEvent() {
	
}
/**
 * 取得房間屬性列表
 * @param r_type	int	房間類型（1=》低級房間，2=》中級房間，3=》高級房間）
 * @return 房間列表新增屬性
 */
roomEvent.prototype.getRoomList = function(r_type) {	
	__debug.trace("getRoomList");
	r_type = (r_type == undefined) ? 0 : r_type;	
	_id_list = __room_list[r_type];
	var _zone = _server.getCurrentZone();
	var _res = [];
		
	if (!__hall[r_type]) return _res;	
	if (__hall[r_type]["race"] == 1) { 
		/* 比赛场房间列表数据
		*  数据格式:
		*   [ [id, name, type, state, maxUser, maxSpec,uCount, speCount, isGame, isLimbo, race, cost, expend, buy, players ], ... ]		
		*/
		for each( var _id in _id_list ) {		
			var _room = _zone.getRoom(_id);
			var _result = [
				_room.getId(),
				String(_room.getName()),
				parseInt(_room.getVariable("type").value),	
				parseInt(_room.getVariable("state").value),			
				_room.getMaxUsers(),
				_room.getMaxSpectator(),
				_room.getAllPlayers().length,
				//_room.getUserCount(),
				_room.getSpectatorCount(),
				_room.isGame(),
				_room.isLimbo(),						
				parseInt(_room.getVariable("race").value),			
				parseInt(_room.getVariable("cost").value),			
				parseInt(_room.getVariable("expend").value),			
				parseInt(_room.getVariable("buy").value),			
				parseInt(_room.getVariable("players").value),															
				];	
			_res.push(_result);
		}
	}else {  
		/* 普通游戏场房间列表数据
		*  数据格式:
		*   [ [id, name, type, state, maxU, maxS, userCount, sperCount, game, limbo, minBlind, maxBlind, minChip, maxChip,], ... ]
		*/
		for each( var _id in _id_list ) {		
			var _room = _zone.getRoom(_id);
			var _result = [
				_room.getId(),
				String(_room.getName()),
				parseInt(_room.getVariable("type").value),			
				parseInt(_room.getVariable("state").value),
				_room.getMaxUsers(),
				_room.getMaxSpectator(),
				_room.getAllPlayers().length,
				parseInt(_room.getVariable("limit").value),	
				//_room.getAllSpectators().length ,
				_room.isGame(),
				_room.isLimbo(),
				parseInt(_room.getVariable("race").value),					
				parseInt(_room.getVariable("minBlind").value),
				parseInt(_room.getVariable("maxBlind").value),
				parseInt(_room.getVariable("minChip").value),
				parseInt(_room.getVariable("maxChip").value),						
				];			
			_res.push(_result);			
		}
	}
	return _res;			
}

/**
 * 獲取大廳列表
 * @return room list {id,name,maxU,maxS,userCount,sperCount,game,limbo,type);
 */
roomEvent.prototype.getHallList = function() {		
	var _room_list = [];	
	for each( var _val in __hall) {			
		var _result = [
			_val["id"],
			_val["name"],	
			_val["race"],
		];
		_room_list.push(_result);
	}		
	return _room_list;
}

/**
 * 會員加入房間
 */
roomEvent.prototype.joinRoom = function(r_user, r_params) {	
	var _room_list = r_user.getRoomsConnected();
	if (!chkParam('roomId', r_params)) {
		return { err:7005 };//參數丟失
	}
	var _current_room_id = -1;
	if (_room_list.length > 0) {
		_current_room_id = _room_list[0];
	}
	var _temp_room = _zone.getRoom(parseInt(r_params.roomId));
	if (_temp_room == null ) {
		return { err:7003 };//房間不存在
	}	
	if ( _temp_room.getPassword() != r_params.pwd ) {
		return { err:7004 };//房間密碼錯誤
	}		
	var _success = _server.joinRoom(r_user, _current_room_id, true, _temp_room.getId(), r_params.pwd, true, false);
	
	//if ( _success ) {		
		return _temp_room;
	//}
	//return { err:7002 };	//加入房間失敗
}

/**
 * 會員離開房間
 * 
 */
roomEvent.prototype.exitRoom = function(r_user, r_room) {	
	var _room_id = r_room.getId();		
	var _hall_id = __hall_room.getId();
	_server.joinRoom(r_user, _room_id, true, _hall_id, '', false, false);	
}


/**
 * 获取成功加入的房间数据
 * @param r_room 
 * @return [roomType, roomId, roomState]
 */
 roomEvent.prototype.getJoinRoomInfo = function(r_room) {
	var _room_vars = [];
	_room_vars.push(__roomVars.getVar(r_room, "type","int"));	//房间类型
	_room_vars.push(r_room.getId());					//房间id
	_room_vars.push(__roomVars.getVar(r_room, 'state',"int")); //房间状态   
	return _room_vars;
 }
 
 /**
  * 获取房间中游戏数据
  * @param r_room
  * @return []
  */
 roomEvent.prototype.getGameInfo = function(r_room) {
	 return [];
 }
 
/**
 * 检查房间状态
 * 如果是普通房间且人数大于1，则开始游戏；
 * 如果是比赛房间人数达到指定人数后开始游戏
 */
roomEvent.prototype.checkRoomState = function(r_room) {
	var _room_state = __roomVars.getState(r_room);  //获取房间状态
	if (_room_state == 1) return; 	//房间中正在进行游戏
	var _users = r_room.getAllPlayers();  // this.getSitPlayers(r_room);	
	var _user_num = _users.length;	
	var _room_type = __roomVars.getVar(r_room, "race", "int");
	if ( _room_type == 1) { 
		//比赛场
		var _players = __roomVars.getVar(r_room, "players", "int");
		if (_user_num == _players) {  //达到设定人数				
			if (_room_state == "free") {
				//房间空闲，开始倒计时，准备开始游戏
				__roomEvent.setInterval(r_room,  2);  
			}
			__debug.trace("race room ,start countdown.");
		}else if (_user_num == 1) {
			__gameEvent.checkBanker(r_room,_users[0]);	//第一个坐下，设置庄家
		}		
	}else {  
		//普通场
		if (_user_num > 1) {  	//人数大于1			
			if (_room_state == "free") {
				//房间空闲，开始倒计时，准备开始游戏
				__roomEvent.setInterval(r_room,  5);  
			}			
			__debug.trace("common room ,start countdown.");
		}else if (_user_num == 1) {
			__gameEvent.checkBanker(r_room,_users[0]);  //第一个坐下，设置庄家
		}
	}
	
	return;	
}

/**
 * 服務器房間計時
 * @param r_room	房間對象
 * @param r_type	計時類別｛game:開始遊戲，ready:準備遊戲，leave:閒置｝
 * @param r_time	計時時長
 */	
roomEvent.prototype.setInterval = function(r_room, r_time) {		
	var _state = __roomVars.getState(r_room);
	if (_state == "free") {
		//房间状态为空闲，执行倒计时
		var _taskid = r_room.getId();
		__schControler.addScheduledTask(_taskid, r_time, false, this.startGame, r_room, this);	
	    __roomVars.setState(r_room, "ready");  //更改房间状态，准备游戏
	}
	return;
}

/**
 * 房间开始游戏
 */
roomEvent.prototype.startGame = function(r_room) {	
	var _users = r_room.getAllPlayers();			
	if (_users.length <= 1) {
		__userEvent.setUserState(r_room, _user, "free");
		return;
	}
	var _user;
	for each(_user in _users) {		
		__userEvent.setUserState(r_room, _user, "play");				
	}
	var _type = __roomVars.getRoomType(r_room);	
	if (_type == 1) { // 比赛房间
		
	}else {   //普通房间
		__gameEvent.gameStart(r_room);
	}	
	
	
}

/**
 * 加入房间
 */
roomEvent.prototype.sit = function(r_room, r_user, r_params) {		
	var _params = { };
	_params._cmd = "sitDown";
	_params.dataObj = { };
	
	//检查玩家是否已坐下
	var _state = __userVars.getState(r_user);	
	if ( _state== "sit" || _state == "play") {
		_params.dataObj = { err:9993 };		
		_server.sendResponse(_params, -1, null, [r_user], 'json');
		return;
	}
		
	//检查座位号是否合法
	if (!chkParam("sit",r_params) && ( r_params['sit'] >= 9 || r_params['sit']< 1) ) {
		_params.dataObj = { err:7006 };	
		_server.sendResponse(_params, -1, null, [r_user], 'json');
		return;
	}
	
	//检查位置是否有人坐
	if ( r_room.getUserByPlayerIndex(r_params['sit']) != null ) {
		_params.dataObj = { err:7007 };
		_server.sendResponse(_params, -1, null, [r_user], 'json');
		return;
	}		
			
	var _chip = __userEvent.exchangeChip(r_user, r_params.chip); //兑换筹码	
	__userEvent.setUserState(r_room, r_user, 'sit', r_params["sit"]);      //设置玩家座位号	
	
	//发送数据
	_params.dataObj = { sit: r_params['sit'], uid:parseInt(r_user.getName()) ,chip:_chip };	
	_server.sendResponse(_params, -1, null, r_room.getAllUsers(), 'json');	
	this.checkRoomState(r_room);  		//检查房间游戏状态
}

/**
 * 加入普通房间
 * @param r_user User
 * @param r_params Object
 * @param r_room Room 
 */
roomEvent.prototype.normalRoomSitdown = function( r_room, r_user, r_params) 
{
	//检查携带筹码是否合法
	var _gold = __userVars.getVar(r_user, 'gold', "int");	//玩家总点数	
	var _max_chip = __roomVars.getVar(r_room, "maxChip", "int");  //房间允许携带最大筹码
	if ( _gold <  parseInt(r_params.chip) ) {								
		if(_gold == 0){  			
			_params.dataObj = { err:7008 };   //玩家点数为0，返回错误码
			_server.sendResponse(_params, -1, null, [r_user], 'json');
			return;
		}
		r_params.chip = _gold;			//帶入籌碼超過擁有的筹码，默认设置为拥有的筹码
	}else if(r_params.chip > _max_chip ){
		r_params.chip = _max_chip;		
	}
	this.sit(r_room, r_user, r_params);
}

/**
 * 加入比赛房间
 * @param r_user
 * @param r_params
 * @param r_room
 */
roomEvent.prototype.raceRoomSitdown = function(r_room, r_user, r_params) {		
	var _buy  = __roomVars.getVar(r_room, "bug", "int");	//购买筹码
	var _cost = __roomVars.getVar(r_room, "cost", "int"); //参赛费用
	var _gold = __userVars.getVar(r_user, "gold", "int");  //自己拥有的点数
	if (_gold < (_bug + _cost) ) {  //点数不够
		var _params = { };
		_params.dataObj = { err:7008 };
		_server.sendResponse(_params, -1, null, [r_user], 'json');
		return;
	}	
	__userEvent.subtractGold(r_user, _cost);  //扣除参赛费用
	r_params.chip = _buy;
	this.sit(r_room, r_user, r_params);	
}









/*  ===================================================  */


///**
 //* 將房間設置為離開狀態
 //* @param r_room	房間對象
 //*/
//roomEvent.prototype.setRoomLeave = function(r_room) {
	//if ( r_room.getUserCount() < 2 ) {
		//var _varList = { };
		//_varList['state'] = 0;
		//_varList['pot'] = 0;//零時傭金
		//_varList['call'] = 0;//最大下注				
		//_varList['deals'] = 0;
		//setRoomVariable(r_room, _varList, false);
		//_varList = { };				
		//_varList['potArr'] = undefined;//池底數組
		//_varList['userArr'] = undefined;//玩家id數組
		//_varList['allIn'] = undefined;
		//_varList['fold'] = undefined;
		//setRoomProVar(r_room, _varList, false);
	//}else {
	//	setRoomVariable(r_room, { state:'1' }, false);
	//}
//}

///**
 //* 將房間設置為準備階段
 //* @param r_room	房間對象
 //*/
//roomEvent.prototype.setRoomReady = function(r_room) {	
	//var _user = r_room.getAllPlayers();	
	//if (_user.length > 1 ) {
		//trace("room: "+r_room.getName()+" is ready to game!");
		//this.setRoomGame(r_room);
		//setRoomVariable(r_room, { state:1 }, false);		
		//__roomEvent.setInterval(r_room, 'game', 2);
	//}else {
		//trace("the " + _user.length + " count player in this room is not enough");		
	//}
//}

/**
 * 開始發牌，遊戲開始
 * 發牌時間為5秒，完成後進入第一位叫牌
 * @param 
 */
roomEvent.prototype.setRoomGame = function(r_room) {
	//發牌間隔時間
	var _userArr = r_room.getAllPlayers();
	var _index_arr = [];
	for each (var _user in _userArr) {
		var _bank = parseInt(_user.getVariable("bank").value);
		trace(_user.getName()+"'s bank is " + _bank);
		if (_bank <= 0) {
			_roomAc.standUp(r_room, _user, { } );
			continue;
		}
		_index_arr.push(_user.getPlayerIndex());
	}
	if (_index_arr.length <= 1) {
		setRoomVariable(r_room, { state:0 }, false);
		return;	//遊戲開始人數不夠
	}
	_index_arr = arraySort(_index_arr, 'asc');
	setRoomProVar(r_room, { sitArr:_index_arr, indexArr:_index_arr } );
	var _param = { };
	_param['banker'] = (r_room.getVariable("banker") == null) ? 0 : parseInt(r_room.getVariable("banker").value);
	_param['index'] = 0;
	_param['news'] = 0;
	_param['deals'] = 0;
	_param['call'] = 0;
	_param['pot'] = 0;
	setRoomVariable(r_room, _param, false);
	_param = { };
	_param['allIn'] = [];
	_param['fold'] = [];
	setRoomProVar(r_room, _param, false);		
	//开始发牌
	setRoomVariable(r_room, { state:2 }, false);
	__gameEvent.formatPokerGame(r_room);
	__log.show("room: "+r_room.getName()+" the game is start!");
}

//
///**
 //* 游戏中有人离开游戏
 //*/
//roomEvent.prototype.someBodyLeave = function(r_room, r_user) {	
	//clearSitIndex(r_room, r_user.getPlayerIndex());
	//var _r_state = r_room.getVariable("state");
	//_r_state = (_r_state == null) ? 0 : parseInt(_r_state.value);
	//if (_r_state == 2) {
		//var _u_state = r_user.getVariable("state");
		//_u_state = (_u_state == null)? 0 : parseInt(_u_state.value);		
		//if (_u_state == 1 ) {
			//__betEvent.fold(r_room, r_user, 0);
			//__userEvent.nextUserAction(r_room, r_user);
			//__gameEvent.checkGameOver(r_room);
		//}
	//}
//}
/**
 * 加入电脑ＡＩ
 */
roomEvent.prototype.joinAIUser = function(r_room) {
	var _user = new AIUser(r_room, parseInt(r_room.getVariable('maxChip').value));
}
